<template>
	<view class="content">
		<view class="status_bar" style="background-color: #FFF;position: fixed;top: 0;left: 0;z-index: 999;">
			<!-- 这里是状态栏 -->
		</view>
		<view style="width: 100%;display: flex;justify-content: space-between; box-sizing: border-box;padding: 12rpx 16rpx;background-color: #FFF;position: fixed;top: 10;left: 0;z-index: 999;" >
			<view style="display: flex;justify-content: flex-start;align-items: center; box-sizing: border-box;">
				<view style="width: 72rpx;" @click="goBack">
					<view style="border: 2rpx solid #E5E6E8;border-radius: 24rpx;">
						<image style="width: 36rpx;height: 36rpx;margin: 16rpx 16rpx 4rpx;" src="/static/images/icon/left-icon.png"></image>
					</view>
				</view>
				<view style="margin-left: 32rpx;display: flex;align-items: center;justify-content: center;">
					<u-image
						:src="currentUser.avatar"
						width="56rpx"
						height="56rpx"
						shape="circle"
					></u-image>
				</view>
				<view style="font-size: 32rpx;color: #232426;margin-left: 16rpx;font-weight: 500;">{{currentUser.nickname}}</view>
				<view style="width: 36rpx;height: 36rpx;border-radius: 50%;background-color: #FFF0D8;margin-left: 16rpx;display: flex;justify-content: center;align-items: center; box-sizing: border-box;">
					<image
						src="/static/images/icon/fire.png"
						style="width:24rpx;height: 24rpx;"
					></image>
				</view>
			</view>
			
			<view style="display: flex;justify-content: flex-end;box-sizing: border-box;align-items: center;gap: 22rpx;">
				<view @click="openToolsFn" style="display: flex;align-items: center;justify-content: center;">
					<image
						src="/static/images/icon/tools-circle.svg"
						style="width:46rpx;height: 46rpx;"
					></image>	
				</view>
			</view>
		</view>
		
		<view class="content">
			<scroll-view 
				scroll-y 
				class="message-box" 
				:scroll-top="scrollTop"
				:scroll-with-animation="true"
				@scroll="onScroll"
			>
				<!-- 时间分隔符 -->
				<view v-for="(timeGroup, groupIndex) in groupedMessages" :key="groupIndex">
					<!-- 时间显示 -->
					<view class="time-divider" v-if="timeGroup.showTime">
					    <text class="time-text">{{ formatGroupTime(timeGroup.timestamp) }}</text>
					</view>
					<!-- 消息列表 -->
					<view 
						v-for="(message, msgIndex) in timeGroup.messages" 
					    :key="message.id"
					    class="message-item"
					>
						<!-- 对方消息 - 左侧 -->
						<view 
							v-if="message.user_id !== currentUser.id"
						    class="message-left"
						>
							<!-- 头像（只在需要时显示） -->
							<u-image
								v-if="shouldShowAvatar(timeGroup.messages, msgIndex)" 
								:src="getOtherUserAvatar(message.user)"
								width="56rpx"
								height="56rpx"
								shape="circle"
							></u-image>
							<view v-else class="avatar-placeholder"></view>
							<!-- 消息内容 -->
							<view class="message-content-wrapper">
								<view class="message-bubble">
									<!-- 文字消息 -->
									<text v-if="message.message_type === 'text'" class="message-text">{{ message.content }}</text>
								
									<!-- 图片消息 -->
									<view v-if="message.message_type === 'image'" class="message-image">
										<image 
											:src="message.content" 
											mode="widthFix" 
											@click="previewImage(message.content)"
										></image>
									</view>
									
									<!-- 卡片消息 -->
									<view v-if="message.message_type === 'card'" class="message-card">
										<text class="card-title">卡片消息</text>
									    <text class="card-content">{{ message.content }}</text>
									</view>
								</view>
							</view>
						</view>
						
						<!-- 本人消息 - 右侧 -->
						<view 
							v-else
						    class="message-right"
						>
							<!-- 消息内容 -->
							<view class="message-content-wrapper own">
								
								<view class="message-bubble own">
									<!-- 文字消息 -->
									<text v-if="message.message_type === 'text'" class="message-text">{{ message.content }}</text>
								
									<!-- 图片消息 -->
									<view v-if="message.message_type === 'image'" class="message-image">
										<image 
											:src="message.content" 
									        mode="widthFix" 
									        @click="previewImage(message.content)"
									    ></image>
									</view>
									
									<!-- 卡片消息 -->
									<view v-if="message.message_type === 'card'" class="message-card">
										<text class="card-title">卡片消息</text>
									    <text class="card-content">{{ message.content }}</text>
									</view>
								</view>
							</view>
							
							<!-- 头像（只在需要时显示） -->
							<u-image
								v-if="shouldShowAvatar(timeGroup.messages, msgIndex)"
								:src="currentUser.avatar || '/static/default-avatar.png'"
								width="56rpx"
								height="56rpx"
								shape="circle"
								@error="onAvatarError"
							></u-image>
							<view v-else class="avatar-placeholder"></view>
						</view>
						
					</view>
				</view>
				
			    <!-- 加载更多提示 -->
			 <!--   <view class="load-more" v-if="isLoading">
					<text>加载中...</text>
			    </view> -->
			</scroll-view>
		</view>
		
		
		<view class="footer" :style="{bottom: keyboardHeight + 'px'}">
			<view style="width: 85%;">
				<u-input
					v-model="inputMessage"
					placeholder="输入消息..."
					border="none"
					:adjust-position="false"
					@keyboardheightchange="handleKeyboardHeightChange"
					@blur="handleBlur"
					:custom-style="{
						backgroundColor: '#F6F8FA',
						borderColor: '#E5E6E8',
						padding:'15rpx 8rpx',
						borderRadius:'32rpx'
					}"
					@confirm="sendMessage"
					@keyup.enter="sendMessage"
				/>
			</view>
			<!-- <button @click="sendMessage">发送</button> -->
			<view @click="sendImgFn">
				<u-image
					src="/static/images/icon/image.png"
					width="48"
					height="48"
				></u-image>
			</view>
			
		</view>
		
		<!--菜單欄-->
		<view v-show="showTools">
			<view class="language" >
				<view class="language-card">
					<view class="language-list">
						<view @click="delRoom" class="language-item language-item-select">
							<view class="language-title">
								刪除此訊息
							</view>
						</view>
						<view @click="Report" class="language-item language-item-select">
							<view class="language-title">
								檢舉使用者
							</view>
						</view>
					</view>
					<view class="language-footer">
						<view class="language-item language-item-btn" @click="showTools=false">Cancel</view>
					</view>
				</view>
			</view>
		</view>
		<!--菜單欄結束-->
		
		<!-- 檢舉組件 -->
		<report-popup
			:show="showReport"
			:targetId="targetUserId"
			:targetType="'user'"
			@close="showReport = false"
		></report-popup>
		
	</view>
</template>

<script>
import { getChatList, sendMsg, getChatNewList } from '@/config/api.js';
import ReportPopup from '@/components/report-popup.vue'
	
export default {
  data() {
		return {
			roomId: '',
			roomName: '',
			messages: [],
			inputMessage: '',
			scrollTop: 0,
			currentUser: {},
			pollInterval: null,
			lastMessageId: 0,
			keyboardHeight: 0,
			isScrollToBottom: true,
			isLoading: false,
			_isActivated: false,
			showTools:false,
			showReport: false,
			targetUserId: '123456' // 被檢舉用戶的ID
		}
	},
	computed:{
		// 分组消息，按时间间隔分组
		groupedMessages(){
			if (!this.messages.length) return [];
			const groups = [];
			let currentGroup = {
				timestamp: new Date(this.messages[0].created_at),
				messages: [],
				showTime: true // 第一组总是显示时间
			};
			  
			this.messages.forEach((message, index) => {
				const messageTime = new Date(message.created_at);
				
				// 检查是否需要创建新组（时间间隔超过5分钟）
				if (index > 0) {
					const prevMessageTime = new Date(this.messages[index - 1].created_at);
					const timeDiff = Math.abs(messageTime - prevMessageTime) / (1000 * 60); // 分钟
				  
					if (timeDiff > 5) {
						// 创建新组
						groups.push(currentGroup);
						currentGroup = {
							timestamp: messageTime,
							messages: [],
							showTime: true
						};
					}
				}
				
				currentGroup.messages.push(message);
			});
			  
			// 添加最后一组
			if (currentGroup.messages.length > 0) {
				groups.push(currentGroup);
			}
			  
			return groups;
		}
	},
	components:{
		ReportPopup
	},
	onLoad(options){
		this.roomId = options.roomId
		this.currentUser = uni.getStorageSync('userInfo')
		this._isActivated = true
		this.loadMessages()
	},
	onShow() {
		// 只有当页面已经加载过且处于激活状态时才启动轮询
		if (this._isActivated && this.roomId) {
		    this.startPolling()
		}
	},  
	onHide() {
	    this.stopPolling()
	},
	onUnload() {
	    this._isActivated = false
	    this.stopPolling()
	    // 清理数据，防止内存泄漏
	    this.roomId = null
	},
	methods: {
		goBack(){
			console.log('返回上一页，停止轮询')
			// 先停止轮询，再导航
			this.stopPolling()
			this._isActivated = false
			uni.navigateBack({
				delta: 1
			})
		},
		handleKeyboardHeightChange(e) {
			this.keyboardHeight = e.detail.height;
			// 滚动到底部
			uni.pageScrollTo({ scrollTop: 99999 });
		},
		handleBlur() {
		  this.keyboardHeight = 0;
		},
		loadMessages(){
			if (this.isLoading) return;
			this.isLoading = true;
			
			let that = this;
			let parames = {
				chat_room_id:this.roomId
			}
			getChatList({data:parames}).then((res) => {
				//success
				console.log('getChatList', res)
				if( res.length > 0 ){
					that.messages = res
					// 设置最后消息ID
					if (that.messages.length > 0) {
						that.lastMessageId = that.messages[that.messages.length - 1].id
					} else {
						that.lastMessageId = 0
					}
					that.isLoading = false;
					
					// 滚动到底部
					setTimeout(() => {
					    this.scrollToBottom()
					}, 300)
				}
			}).catch((e) =>{
				console.log('加载消息失败:', e)
			})
		},
		
		startPolling() {
			this.stopPolling() // 先停止现有的轮询
			
			// 检查页面状态
			if (!this._isActivated || !this.roomId) {
				console.log('页面未激活，不启动轮询')
				return
			}
		  
			// 每3秒轮询一次新消息
			this.pollInterval = setInterval(() => {
				// 再次检查页面状态
				if (this._isActivated && this.roomId) {
				  this.checkNewMessages()
				}
			}, 3000)
		  
			console.log('开始轮询消息')
		},
		
		stopPolling() {
			if (this.pollInterval) {
				clearInterval(this.pollInterval)
				this.pollInterval = null
				console.log('停止輪詢')
			}
		},
		checkNewMessages(){
			// 如果没有最后消息ID，不进行轮询
			if (this.lastMessageId === null || this.isLoading) {
			    console.log('如果没有最后消息ID，不进行轮询')
				return
			}
			this.isLoading = true;
			
			let that = this;
			let parames = {
				chat_room_id:this.roomId,
				last_message_id:this.lastMessageId
			}
			getChatNewList({data:parames}).then((res) => {
				//success
				console.log('getChatNewList', res)
				if (res.length > 0) {
					// 添加新消息到列表
					that.messages.push(...res)
					// 更新最后消息ID为最新消息的ID
					that.lastMessageId = res[res.length - 1].id
					// 只有当前在底部时才自动滚动
					if (this.isScrollToBottom) {
					    setTimeout(() => {
							this.scrollToBottom()
					    }, 100)
					}
				}
				that.isLoading = false;
			}).catch((e) =>{
				console.log('加载消息失败:', e)
			})
		},
		sendMessage(){
			if (!this.inputMessage.trim()) return
			let that = this;
			let parames = {
				chat_room_id:this.roomId,
				content:this.inputMessage,
				message_type:'text'
			}
			sendMsg(parames).then((res) => {
				//success
				that.inputMessage = ''
				that.messages.push(res)
				that.lastMessageId = res.id
				that.$nextTick(() => {
					setTimeout(() => {
					    this.scrollToBottom()
					}, 300)
				})
			}).catch((e) =>{
				console.log('加载消息失败:', e)
			})
		},
		sendImgFn(){
			let that = this;
			let uploadUrl = uni.$u.http.config.baseURL+'/api/home/upload'
			
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				// sourceType: ['album'],
				success: (chooseImageRes) => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					for (let i = 0; i < tempFilePaths.length; i++) {
						uni.uploadFile({
							url: uploadUrl,
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token') // 从全局获取token
							},
							filePath: tempFilePaths[i],
							name: 'file',
							formData: {
								'type': 'chat',
								'timestamp': Date.now()
							},
							success: (uploadFileRes) => {
								let res = JSON.parse(uploadFileRes.data)
								that.sendMsgWithImg(res.fullurl)
							}
						});
					}
				}
			});
		},
		sendMsgWithImg(src){
			let that = this;
			let parames = {
				chat_room_id:this.roomId,
				content:src,
				message_type:'image'
			}
			sendMsg(parames).then((res) => {
				//success
				that.messages.push(res)
				that.lastMessageId = res.id
				that.$nextTick(() => {
					setTimeout(() => {
					    this.scrollToBottom()
					}, 300)
				})
			}).catch((e) =>{
				console.log('加载消息失败:', e)
			})
		},
		// 判断是否显示头像
		shouldShowAvatar(messages, currentIndex) {
		  // 如果是第一条消息，显示头像
		  if (currentIndex === 0) return true;
		  
		  const currentMessage = messages[currentIndex];
		  const prevMessage = messages[currentIndex - 1];
		  
		  // 如果上一条消息是不同用户发送的，显示头像
		  return currentMessage.user_id !== prevMessage.user_id;
		},
		
		// 获取对方用户头像
		getOtherUserAvatar(user) {
		  return user?.avatar || '/static/default-avatar.png';
		},
		
		// 格式化组时间（显示日期）
		formatGroupTime(timestamp) {
		      const now = new Date();
		      const messageDate = new Date(timestamp);
		      
		      // 今天：只显示时间 H:i
		      if (messageDate.toDateString() === now.toDateString()) {
		        return this.formatTime(messageDate);
		      }
		      
		      // 不是今天：显示 m-d H:i
		      return this.formatDateWithTime(messageDate);
		},
		// 格式化时间为 H:i
		formatTime(date) {
		  const hours = date.getHours().toString().padStart(2, '0');
		  const minutes = date.getMinutes().toString().padStart(2, '0');
		  return `${hours}:${minutes}`;
		},
		
		// 格式化日期为 m-d H:i
		formatDateWithTime(date) {
		  const month = (date.getMonth() + 1).toString().padStart(2, '0');
		  const day = date.getDate().toString().padStart(2, '0');
		  const time = this.formatTime(date);
		  return `${month}-${day} ${time}`;
		},
		
		scrollToBottom() {
			// this.scrollTop = Math.random() * 1000000
			// this.isScrollToBottom = true
			this.$nextTick(() => {
			    setTimeout(() => {
			      // 方法1：使用 uni.pageScrollTo
			      uni.pageScrollTo({
			        scrollTop: 999999,
			        duration: 0
			      })
			      
			      // 方法2：同时设置 scrollTop
			      this.scrollTop = Date.now() // 使用时间戳确保唯一性
			    }, 200)
			})
		},
		onScroll(e) {
			const { scrollHeight, scrollTop, clientHeight } = e.detail
			this.isScrollToBottom = (scrollHeight - scrollTop - clientHeight) < 50
		},
		previewImage(url) {
		    uni.previewImage({
		        urls: [url]
		    })
		},
		onAvatarError(e) {
			console.log('头像加载失败:', e)
		},
		openToolsFn(){
			this.showTools = true;
		},
		//刪除聊天室
		delRoom(){
			
		},
		//檢舉使用者
		Report(){
			this.showReport = true;
			this.showTools = false;
		},
	}
}
</script>
<style lang="scss" scoped>
.content{
	position: relative;
	height: 100vh;
	background-color: #F6F8FA;
	box-sizing: border-box;
	padding-top: var(--status-bar-height);
	
	.message-box{
		background-color: #F6F8FA;
		padding:120rpx 30rpx;
		box-sizing: border-box;
	}
	
	.footer{
		background-color: #FFF;
		display: flex;
		justify-content: space-around;
		align-items: center;
		position: fixed;
		left: 0;
		right: 0;
		padding: 10px 20rpx;
		transition: all 0.3s;
		
		input{
			flex: 1;
			height: 40px;
			padding: 0 10px;
			border: 1px solid #eee;
		}
	}
	.chat-room {
	  height: 100vh;
	  display: flex;
	  flex-direction: column;
	  background-color: #f5f5f5;
	}
	
	.header {
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	  padding: 20rpx 30rpx;
	  background-color: #fff;
	  border-bottom: 1rpx solid #eee;
	  height: 100rpx;
	  box-sizing: border-box;
	}
	
	.back {
	  font-size: 40rpx;
	  color: #007aff;
	  width: 60rpx;
	}
	
	.title {
	  font-size: 36rpx;
	  font-weight: bold;
	  flex: 1;
	  text-align: center;
	}
	
	.delete-btn {
	  font-size: 28rpx;
	  color: #ff3b30;
	  width: 60rpx;
	  text-align: right;
	}
	
	.message-list {
	  flex: 1;
	  padding: 20rpx;
	  background-color: #f5f5f5;
	}
	
	/* 时间分隔符 */
	.time-divider {
	  display: flex;
	  justify-content: center;
	  margin: 40rpx 0;
	}
	
	.time-text {
	  color: #555555;
	  font-size: 22rpx;
	  padding: 8rpx 20rpx;
	}
	
	.message-item {
	  margin-bottom: 20rpx;
	}
	
	/* 左侧消息（对方） */
	.message-left {
	  display: flex;
	  align-items: flex-start;
	}
	
	/* 右侧消息（本人） */
	.message-right {
	  display: flex;
	  align-items: flex-start;
	  justify-content: flex-end;
	}
	
	.avatar {
	  width: 56rpx;
	  height: 56rpx;
	  border-radius: 10rpx;
	  flex-shrink: 0;
	}
	
	.avatar-placeholder {
		width: 56rpx;
		height: 56rpx;
		flex-shrink: 0;
	}
	
	/* 消息内容包装器 */
	.message-content-wrapper {
	  max-width: 500rpx;
	  margin: 0 20rpx;
	  display: flex;
	  flex-direction: column;
	}
	
	.message-content-wrapper.own {
	  align-items: flex-end;
	}
	
	/* 消息气泡 */
	.message-bubble {
	  background-color: #fff;
	  padding: 20rpx;
	  border-radius: 10rpx;
	  position: relative;
	  max-width: 100%;
	  word-break: break-word;
	}
	
	.message-bubble.own {
	  background-color: #C5EBF6;
	}
	
	/* 消息气泡三角形（可选） */
	.message-bubble::before {
	  content: '';
	  position: absolute;
	  top: 20rpx;
	  width: 0;
	  height: 0;
	  border: 10rpx solid transparent;
	}
	
	.message-left .message-bubble::before {
	  left: -20rpx;
	  border-right-color: #fff;
	}
	
	.message-right .message-bubble::before {
	  right: -20rpx;
	  border-left-color: #C5EBF6;
	}
	
	.message-text {
	  font-size: 32rpx;
	  line-height: 1.4;
	}
	
	.message-image image {
	  max-width: 300rpx;
	  border-radius: 10rpx;
	}
	
	.message-card {
	  background-color: #f8f8f8;
	  padding: 20rpx;
	  border-radius: 8rpx;
	  border: 1rpx solid #e0e0e0;
	  min-width: 200rpx;
	}
	
	.card-title {
	  font-size: 28rpx;
	  color: #666;
	  display: block;
	  margin-bottom: 10rpx;
	}
	
	.card-content {
	  font-size: 26rpx;
	  color: #333;
	}
	
	.message-time {
	  font-size: 22rpx;
	  color: #999;
	  margin-top: 8rpx;
	  text-align: center;
	}
	
	.load-more {
	  text-align: center;
	  padding: 20rpx;
	  color: #999;
	  font-size: 24rpx;
	}
	
	.input-area {
	  display: flex;
	  align-items: center;
	  padding: 20rpx;
	  background-color: #fff;
	  border-top: 1rpx solid #eee;
	  min-height: 120rpx;
	  box-sizing: border-box;
	}
	
	.message-input {
	  flex: 1;
	  border: 1rpx solid #ddd;
	  border-radius: 10rpx;
	  padding: 20rpx;
	  margin-right: 20rpx;
	  font-size: 28rpx;
	  background-color: #f8f8f8;
	}
	
	.send-btn {
	  background-color: #007aff;
	  color: #fff;
	  border-radius: 10rpx;
	  padding: 20rpx 40rpx;
	  font-size: 28rpx;
	}
	
	.send-btn:disabled {
	  background-color: #ccc;
	  color: #999;
	}
	.language{
		position: fixed; /* 固定定位 */
		top: 0;
		left: 0;
		width: 100%; /* 宽度100% */
		height: 100%; /* 高度100% */
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 999;
	}
	.language-card{
		position: fixed;
		bottom: 68rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
		width: 718rpx;
	}
	.language-list{
		
	}
	.language-list .language-item-select:first-of-type{
		border-radius: 24rpx 24rpx 0 0;
	}
	.language-list .language-item-select:last-of-type{
		border-radius: 0 0 24rpx 24rpx;
		border-bottom:0;
	}
	.language-item{
		padding: 34rpx 0;
		background: rgba(255, 255, 255, 0.7);
		text-align: center;
		// margin: 0.5rpx auto;
		border-bottom:1rpx solid #ABABAB;
	}
	.language-title{
		color: #007AFF;
		font-size: 34rpx;
	}
	.language-tips{
		font-size: 34rpx;
		color: #AEAEAE;
	}
	.language-footer{
		margin-top: 16rpx;
	}
	.language-item-btn{
		font-weight: 600;
		color: #007AFF;
		border-radius: 24rpx;
	}
}
</style>
